<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <Authority :value="'api.swagger'">
          <a-button type="primary" @click="handleImportSwagger"> 导入Swagger接口 </a-button>
        </Authority>
        <Authority :value="'api.add'">
          <a-button type="primary" @click="handleCreate"> 新增接口 </a-button>
        </Authority>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="[
            {
              icon: 'clarity:note-edit-line',
              auth: 'api.edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              auth: 'api.del',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]" />
        </template>
      </template>
    </BasicTable>
    <ApiDrawer @register="registerDrawer" @success="handleSuccess" />
    <ImportApiDrawer @register="ImortSwaggerRegisterDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { getApiPage, removeApi } from '/@/api/system/api';
import { useDrawer } from '/@/components/Drawer';
import { Authority } from '/@/components/Authority';
import ApiDrawer from './ApiDrawer.vue';
import ImportApiDrawer from './ImportApiDrawer.vue';
import { columns, searchFormSchema } from './api.data';

const [registerDrawer, { openDrawer }] = useDrawer();
const [ImortSwaggerRegisterDrawer, ImortSwaggerMethods] = useDrawer();
const [registerTable, { reload }] = useTable({
  title: '接口列表',
  api: getApiPage,
  columns,
  formConfig: {
    labelWidth: 90,
    schemas: searchFormSchema,
  },
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 80,
    title: '操作',
    dataIndex: 'action'
  },
});

function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
}

function handleImportSwagger() {
  ImortSwaggerMethods.openDrawer(true, {
    isUpdate: false,
  });
}

function handleEdit(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
  });
}

async function handleDelete(record: Recordable) {
  await removeApi([record['id']]);
  reload();
}

function handleSuccess() {
  reload();
}
</script>